<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="text-center mb-6">
        <h1 class="text-3xl font-bold">五子棋</h1>
        <p class="text-sm text-gray-600">15x15 棋盘，轮流落子，五子连珠获胜。</p>
      </div>

      <div class="bg-white rounded-lg shadow p-4">
        <div class="flex items-center justify-between mb-3">
          <div>当前：<span class="font-medium">{{ current === 1 ? '黑子' : '白子' }}</span></div>
          <div>分数: <span class="font-medium">{{ moves }}</span></div>
          <div>
            <button class="px-3 py-1 bg-blue-600 text-white rounded" @click="reset">重置</button>
          </div>
        </div>

        <div class="overflow-auto">
          <div class="grid" :style="gridStyle">
            <div v-for="(cell, idx) in boardFlat" :key="idx"
              class="w-8 h-8 border border-gray-300 flex items-center justify-center bg-[#f8f8f8] cursor-pointer"
              @click="place(idx)">
              <div v-if="cell === 1" class="w-6 h-6 rounded-full bg-black"></div>
              <div v-else-if="cell === 2" class="w-6 h-6 rounded-full bg-white border"></div>
            </div>
          </div>
        </div>

        <div v-if="winner" class="mt-4 p-3 bg-green-50 rounded">
          <strong>{{ winnerText }}</strong>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
const SIZE = 15
const board = ref(Array(SIZE).fill(null).map(()=>Array(SIZE).fill(0)))
const current = ref(1) // 1 黑，2 白
const winner = ref(0)
const moves = ref(0)

const boardFlat = computed(() => board.value.flat())
const gridStyle = computed(() => ({
  display: 'grid',
  gridTemplateColumns: `repeat(${SIZE}, 32px)`,
  gap: '0px'
}))

function reset(){
  for(let r=0;r<SIZE;r++) for(let c=0;c<SIZE;c++) board.value[r][c]=0
  current.value = 1
  winner.value = 0
  moves.value = 0
}

function idxToRC(idx){
  return [Math.floor(idx / SIZE), idx % SIZE]
}

function place(idx){
  if (winner.value) return
  const [r,c] = idxToRC(idx)
  if (board.value[r][c] !== 0) return
  board.value[r][c] = current.value
  moves.value++
  if (checkWin(r,c)) {
    winner.value = current.value
  } else {
    current.value = current.value === 1 ? 2 : 1
  }
}

function checkWin(r,c){
  const player = board.value[r][c]
  const dirs = [[1,0],[0,1],[1,1],[1,-1]]
  for(const [dr,dc] of dirs){
    let count = 1
    // forward
    let rr=r+dr, cc=c+dc
    while(inBounds(rr,cc) && board.value[rr][cc]===player){ count++; rr+=dr; cc+=dc }
    // backward
    rr=r-dr; cc=c-dc
    while(inBounds(rr,cc) && board.value[rr][cc]===player){ count++; rr-=dr; cc-=dc }
    if (count>=5) return true
  }
  return false
}

function inBounds(r,c){ return r>=0 && r<SIZE && c>=0 && c<SIZE }

const winnerText = computed(()=> winner.value ? (winner.value===1? '黑子获胜' : '白子获胜') : '')
</script>

<style scoped>
.grid { max-width: 100%; }
</style>
